// server/src/scripts/initAdmin.ts
import { prisma } from '../lib/prisma'
import { hashPassword } from '../utils/auth'

const initAdmin = async () => {
  try {
    const adminUsername = process.env.ADMIN_USERNAME || 'admin'
    const adminEmail = process.env.ADMIN_EMAIL || 'admin@myway.com'
    const adminPassword = process.env.ADMIN_PASSWORD || 'admin123'

    // 检查是否已存在管理员用户
    const existingAdmin = await prisma.user.findFirst({
      where: {
        OR: [
          { username: adminUsername },
          { email: adminEmail }
        ]
      }
    })

    if (existingAdmin) {
      console.log('✅ 管理员用户已存在')
      return
    }

    // 创建管理员用户
    const hashedPassword = await hashPassword(adminPassword)
    
    await prisma.user.create({
      data: {
        username: adminUsername,
        email: adminEmail,
        password: hashedPassword,
        role: 'ADMIN',
        isActive: true
      }
    })

    console.log('✅ 管理员用户创建成功')
    console.log(`👤 用户名: ${adminUsername}`)
    console.log(`📧 邮箱: ${adminEmail}`)
    console.log(`🔑 密码: ${adminPassword}`)
    console.log('⚠️  请尽快修改默认密码！')
    
  } catch (error) {
    console.error('❌ 初始化管理员用户失败:', error)
  } finally {
    await prisma.$disconnect()
  }
}

// 如果是直接运行此文件
if (require.main === module) {
  initAdmin()
}

export { initAdmin }